<script setup lang="ts">
import { onMounted, ref } from "vue";
import type { RecentArticlesVo } from "@/type";
import { postApi } from "@/api";
import dayjs from "dayjs";
import { filterHtmlTags, truncateString } from "@/utils";
import { useRouter } from "vue-router";

const router = useRouter();
const recentArticles = ref<RecentArticlesVo[]>([]);
const getRecent = async () => {
  const res = await postApi.getRecent();
  recentArticles.value = res.map((item: RecentArticlesVo) => {
    return {
      ...item,
      title: truncateString(filterHtmlTags(item.title), 20),
      createdAt: dayjs(item.createdAt).format("YYYY-MM-DD"),
    };
  });
};
const toItem = (article: RecentArticlesVo) => {
  router.push(`/item/${article.title}/${article.id}`);
};
onMounted(() => {
  getRecent();
});
</script>

<template>
  <div class="bg-white rounded-lg shadow-sm p-6">
    <h3 class="text-lg font-bold mb-4">相关文章</h3>
    <div class="space-y-4">
      <div
        v-for="article in recentArticles"
        :key="article.id"
        class="flex space-x-3 cursor-pointer group"
      >
        <img
          :src="article.coverImage"
          :alt="article.title"
          class="!w-20 !h-15 rounded object-coverImage"
        />
        <div>
          <h4
            class="font-medium transition-all group-hover:text-blue-600 line-clamp-2"
            @click="toItem(article)"
          >
            {{ article.title }}
          </h4>
          <p class="text-sm text-gray-500 mt-1">{{ article.createdAt }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
